﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Db4objects.Db4o;

namespace WebGetter
{
    class PageRepository : BaseRespository<Page>, IPageRepository
    {
        const string dbPath = "pages.db4o";

        protected override IObjectContainer GetDb()
        {
            return Db4oEmbedded.OpenFile(dbPath);
        }

        public Page GetPageByUrl(string url)
        {
            using (var db = GetDb())
            {
                return db.Query<Page>(p => p.Url == url).SingleOrDefault();
            }
        }

        public IEnumerable<Reply> GetReplies(Page page)
        {
            IEnumerable<Reply> replies = new List<Reply>();
            using (var db = GetDb())
            {
                var pages = db.Query<Page>(p => p.Url == page.Url);
                if (pages.Count > 0)
                {
                    replies = pages[0].Replies;
                }
            }

            return replies;
        }


        public Page GetLastVisitedPage()
        {
            using (var db = GetDb())
            {
                var visitLog = db.Query<VisitLog>().OrderBy(v => v.LeaveTime).Take(1).Single();
                return db.Query<Page>(p => p.VistLogs.Contains(visitLog)).SingleOrDefault();
            }
        }
    }
}
